<template>
  <el-dialog
          :model-value="dialogUploadVisible"
          :title="dialogUploadTitle"
          :before-close="handleCancelUploadDialog"
          width="60%"
  >
    <el-row>
      <el-col :span="24">
        <el-upload
                :action="uploadAction"
                multiple
                name="upfile"
                :data="uploadFormData"
                :show-file-list="false"
                :auto-upload="false"
                :on-success="handleUploadSuccess"
                :on-error="handleUploadError"
                :on-change="handleChangeFile"
                :with-credentials="true"
        >
          <el-button type="primary" size="mini">
            <el-icon>
              <plus />
            </el-icon>
            选择文件
          </el-button>
        </el-upload>
      </el-col>
      <el-col :span="24" class="mt10">
        <el-table :data="uploadFormData.fileList" style="width: 100%">
          <el-table-column label="预览" width="60">
            <template #default="{row}">
              <el-image
                      :src="row.viewurl"
              />
            </template>
          </el-table-column>
          <el-table-column label="文件名称" prop="filename"></el-table-column>
          <el-table-column label="文件FID" prop="fid" />
          <el-table-column label="文件大小">
            <template #default="{row}">
              {{formatSize(row.filesize)}}
            </template>
          </el-table-column>
          <el-table-column label="分辨率">
            <template #default="{row}">
              {{row.width + '*' + row.height}}
            </template>
          </el-table-column>
          <el-table-column label="上传进度">
            <template #default="{row}">
              <el-progress :percentage="row.progress" :text-inside="true" :stroke-width="18" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150px">
            <template #default="{row}">
              <el-button type="primary" size="mini" @click="handleUploadFile(row)">上传</el-button>
              <el-button type="danger" size="mini" @click="handleDeleteFile(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <template #footer>
      <div align="center">
        <el-button type="default" size="mini" @click="handleCancelUploadDialog">取消</el-button>
        <el-button type="primary" size="mini" @click="handleUploadAllFile">全部上传</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
  import {Plus} from "@element-plus/icons"
  import {ref, reactive} from 'vue'
  import {formatSize} from "@/utils/usage-config";
  import {getFileFid} from "@/utils/upload";
  import {submitPostUploadFile} from "@/api/package/material";

  export default {
    name: "UploadFile",
    props: {
      dialogUploadVisible: {
        type: Boolean,
        default: false
      },
      dialogUploadPath: {
        type: String,
        required: true
      },
      dialogUploadTitle: {
        type: String,
        required: true
      }
    },
    components: {Plus},
    emits: ['handleCancelUploadDialog', 'reloadFileList'],
    setup(props, context) {
      const uploadAction = ref(process.env.VUE_APP_BASE_MEDIA_API + '/console/cloudstorage/image/upload')
      const uploadFormData = reactive({
        path: props.dialogUploadPath,
        fileList: []
      })

      const handleCancelUploadDialog = () => {
        context.emit('handleCancelUploadDialog')
      }
      const handleUploadSuccess = (response) => {
        console.log(response);
      }
      const handleUploadError = (err) => {
        console.log(err);
      }
      const handleChangeFile = (file) => {
        getFileFid(file).then(fid => {
          const image = new Image()
          image.src = URL.createObjectURL(file.raw)
          image.onload = function() {
            uploadFormData.fileList.push({
              path: uploadFormData.path.trim('/'),
              viewurl: image.src,
              filename: file.name,
              filesize: file.size,
              width: image.width,
              height: image.height,
              fid: fid,
              upfile: file,
              progress: 0
            })
          }
        })
      }

      const handleUploadFile = (fileinfo) => {
        console.log(fileinfo.path);
        doUploadFile(fileinfo)
      }
      const handleUploadAllFile = () => {
        uploadFormData.fileList.forEach(fileinfo => {
          doUploadFile(fileinfo)
        })
      }
      const doUploadFile = (fileinfo) => {
        // 分片大小
        let chunkSize = 2097152
        // 文件信息
        const upfile = fileinfo.upfile
        // 总片数
        let chunks = Math.ceil(upfile.size / chunkSize)
        // 当前分片索引
        let currentChunk = 0
        let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice
        for (let i = 0; i < upfile.size; i += chunkSize) {
          let tmp = blobSlice.call(upfile.raw, i, Math.min(upfile.size, (i + chunkSize)))
          const formData = new FormData()
          formData.append('chunks', chunks)
          formData.append('currentChunk', currentChunk)
          formData.append('upfile', tmp)
          formData.append('path', fileinfo.path)
          formData.append('fid', fileinfo.fid)
          submitPostUploadFile(formData).then(response => {
            currentChunk++
            let percentage = (currentChunk / chunks) * 100
            fileinfo.progress = parseFloat(percentage.toFixed(2))
            console.log(response);
          })
        }
      }
      const handleDeleteFile = (fileinfo) => {
        const index = uploadFormData.fileList.findIndex(item => item.fid == fileinfo.fid)
        uploadFormData.fileList.splice(index, 1)
      }

      return {
        uploadAction,
        uploadFormData,
        handleUploadSuccess,
        handleUploadError,
        handleChangeFile,
        formatSize,
        handleUploadFile,
        handleDeleteFile,
        handleUploadAllFile,
        handleCancelUploadDialog
      }
    }
  }
</script>

<style scoped>

</style>
